package com.jinlejia.erp.ui.mine.client;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jinlejia.erp.R;
import com.jinlejia.erp.bean.Clients;
import com.jinlejia.erp.databinding.ActivityContactsListBinding;
import com.jinlejia.erp.ui.common.PermissionDialog;
import com.jinlejia.erp.ui.mine.adapter.ContactsListAdapter;
import com.jinlejia.erp.utils.CharacterParser;
import com.jinlejia.erp.utils.PinyinComparator;
import com.weight.CustomToast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 从通宵录添加客户信息
 */

public class ContactsListActivity extends AppCompatActivity {

    private ContactsListAdapter adapter;
    private ArrayList<Clients> dateList = new ArrayList<>();
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<Clients> SourceDateList = new ArrayList<>();

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;


    private ActivityContactsListBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_contacts_list);
        binding.setEvent(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        binding.btBack.setOnClickListener(view -> finish());

        //设置右侧触摸监听
        binding.idSideBar.setOnTouchingLetterChangedListener(s -> {
            //该字母首次出现的位置
            if (adapter != null) {
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    binding.idListView.setSelection(position);
                }
            }
        });

        binding.idListView.setOnItemClickListener((adapterView, view, position, l) -> {
            //这里要利用adapter.getItem(position)来获取当前position所对应的对象
            //选择的联系人
            Intent intent = new Intent();
            intent.putExtra("name", ((Clients) adapter.getItem(position)).getName());
            intent.putExtra("tel", ((Clients) adapter.getItem(position)).getTel());
            setResult(RESULT_OK, intent);
            finish();
        });
    }

    private void initView() {
        binding.idListView.setEmptyView(binding.idEmpty);//设置空布局
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();


        if (XXPermissions.isHasPermission(ContactsListActivity.this, Permission.Group.CONTACTS)) {
            //已经授权
            dateList = getPhoneNumberFromMobile(this);
            SourceDateList = filledData(dateList);

            // 根据a-z进行排序源数据
            Collections.sort(SourceDateList, pinyinComparator);
            adapter = new ContactsListAdapter(this, SourceDateList);
            binding.idListView.setAdapter(adapter);
        } else {
            //未授权
            XXPermissions.with(this)
                    .permission(Permission.READ_CONTACTS) //不指定权限则自动获取清单中的危险权限
                    .request(new OnPermission() {

                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            if (isAll) {
                                dateList = getPhoneNumberFromMobile(ContactsListActivity.this);
                                SourceDateList = filledData(dateList);

                                // 根据a-z进行排序源数据
                                Collections.sort(SourceDateList, pinyinComparator);
                                adapter = new ContactsListAdapter(ContactsListActivity.this, SourceDateList);
                                binding.idListView.setAdapter(adapter);
                            }
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            PermissionDialog permissionDialog = new PermissionDialog(ContactsListActivity.this);
                            permissionDialog.show();
                            permissionDialog.setConfirmListener(() -> XXPermissions.gotoPermissionSettings(ContactsListActivity.this));
                        }
                    });
        }

    }

    public ArrayList<Clients> getPhoneNumberFromMobile(Context context) {
        // TODO Auto-generated constructor stub
        ArrayList<Clients> list = new ArrayList<>();
        Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, null, null, null);
        if (cursor != null) {
            //moveToNext方法返回的是一个boolean类型的数据
            while (cursor.moveToNext()) {
                //读取通讯录的姓名
                String name = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                //读取通讯录的号码
                String number = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                Clients clients = new Clients();
                clients.setName(name);
                clients.setTel(number.replaceAll("-", "").replaceAll("\\s", ""));
                list.add(clients);
            }
        } else {
            CustomToast.showToast(ContactsListActivity.this, "请查看是否开启权限", 2000);
        }
        return list;
    }

    /**
     * 为ListView填充数据
     *
     * @param
     * @return
     */
    private List<Clients> filledData(ArrayList<Clients> data) {
        List<Clients> mSortList = new ArrayList<>();

        for (int i = 0; i < data.size(); i++) {
            Clients clients = new Clients();
            clients.setName(data.get(i).getName());
            clients.setTel(data.get(i).getTel());
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(data.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                clients.setSortLetters(sortString.toUpperCase());
            } else {
                clients.setSortLetters("#");
            }

            mSortList.add(clients);
        }
        return mSortList;

    }

}
